<template>
    <div class="data-index">
        <h2>作业数据分析</h2>
        <div class="filters">
            <el-select v-model="selectedCourse" placeholder="选择课程" @change="handleCourseChange">
                <el-option
                    v-for="course in courses"
                    :key="course.courseclassT"
                    :label="course.courseclassT"
                    :value="course.courseclassT"
                ></el-option>
            </el-select>
            <el-select 
                v-model="selectedAssignment" 
                placeholder="选择作业" 
                @change="handleAssignmentChange"
            >
                <el-option
                    v-for="assignment in assignments"
                    :key="assignment.id"
                    :label="assignment.homeworkName"
                    :value="assignment.id"
                ></el-option>
            </el-select>
            <el-button type="primary" @click="analyzeData">分析数据</el-button>
        </div>

        <!-- 统计卡片区域 -->
        <div class="card-row">
            <el-card class="stat-card">
                <template #header>
                    <div class="card-header">
                        <span>提交统计</span>
                    </div>
                </template>
                <div class="stat-content">
                    <div class="stat-item">
                        <span class="label">已交人数：</span>
                        <span class="value">{{ submissionData.datasets[0].data[0] }}</span>
                    </div>
                    <div class="stat-item">
                        <span class="label">未交人数：</span>
                        <span class="value">{{ submissionData.datasets[0].data[1] }}</span>
                    </div>
                    <div class="stat-item">
                        <span class="label">总人数：</span>
                        <span class="value">{{ submissionData.datasets[0].data[0] + submissionData.datasets[0].data[1] }}</span>
                    </div>
                </div>
            </el-card>
            
            <el-card class="stat-card">
                <template #header>
                    <div class="card-header">
                        <span>成绩统计</span>
                    </div>
                </template>
                <div class="stat-content">
                    <div class="stat-item">
                        <span class="label">最高分：</span>
                        <span class="value">{{ maxScore }}</span>
                    </div>
                    <div class="stat-item">
                        <span class="label">最低分：</span>
                        <span class="value">{{ minScore }}</span>
                    </div>
                    <div class="stat-item">
                        <span class="label">平均分：</span>
                        <span class="value">{{ avgScore }}</span>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 图表区域 -->
        <div class="card-row">
            <el-card class="chart-card">
                <h3>交作业情况</h3>
                <el-pie-chart :data="submissionData"></el-pie-chart>
            </el-card>
            <el-card class="chart-card">
                <h3>成绩分布</h3>
                <el-bar-chart 
                    ref="scoreChart" 
                    :data="scoreDistribution"
                    :options="{
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    stepSize: 1
                                }
                            }
                        },
                        plugins: {
                            legend: {
                                display: false
                            }
                        }
                    }"
                    style="height: 300px;"
                ></el-bar-chart>
            </el-card>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import ElPieChart from './PieChart.vue';
import ElBarChart from './BarChart.vue';

export default {
    components: {
        ElPieChart,
        ElBarChart
    },
    data() {
        return {
            courses: [],
            assignments: [],
            homeworkList: [],
            selectedCourse: '',
            selectedAssignment: '',
            // 成绩统计数据
            maxScore: 0,
            minScore: 0,
            avgScore: '0.00',
            // 提交情况数据
            submissionData: {
                labels: ['已交', '未交'],
                datasets: [{
                    data: [0, 0],
                    backgroundColor: ['#409EFF', '#67C23A']
                }]
            },
            // 成绩分布数据
            scoreDistribution: {
                labels: ['0-59', '60-69', '70-79', '80-89', '90-100'],
                datasets: [{
                    label: '学生人数',
                    data: [0, 0, 0, 0, 0],
                    backgroundColor: '#409EFF'
                }]
            }
        };
    },
    created() {
        this.fetchCourses();
    },
    methods: {
        async fetchCourses() {
          try {
                this.loading = true;
                this.userInfo = JSON.parse(localStorage.getItem('users'));
                if (!this.userInfo || !this.userInfo.userId) {
                    this.$message.error('未找到用户信息，请重新登录');
                    return;
                }

                const response = await axios.post('http://localhost:9999/teach/getTeach', 
                    this.userInfo,
                    {
                        headers: {
                            'Content-Type': 'application/json;charset=UTF-8'
                        }
                    }
                );

                if (!response.data) {
                    this.$message.info('未获取到课程数据');
                    return;
                }

                this.courses = Array.isArray(response.data) ? response.data : [];
                
            
            } catch (error) {
                console.error('获取师课程失败:', error.response || error);
                
            } finally {
                this.loading = false;
            }
        },
        
        async analyzeData() {
            try {
                // 重置所有数据
                this.resetData();

                // 验证必要参数
                if (!this.selectedCourse || !this.selectedAssignment) {
                    this.$message.warning('请选择班级和作业');
                    return;
                }

                const courseclass = this.selectedCourse;
                const homeworkId = parseInt(this.selectedAssignment);

                // 获取成绩统计数据
                const scoreResponse = await axios.get('http://localhost:9999/finish/getScore', {
                    params: { 
                        courseclass: this.selectedCourse,
                        homeworkId: this.selectedAssignment
                    }
                });

                if (scoreResponse.data && scoreResponse.data.length > 0) {
                    const data = scoreResponse.data[0];
                    this.maxScore = data.scoreMax || 0;
                    this.minScore = data.scoreMin || 0;
                    this.avgScore = data.scoreAvg ? parseFloat(data.scoreAvg).toFixed(2) : '0.00';
                }

                // 获取已提交作业的总数
                const finishedTotalResponse = await axios.get('http://localhost:9999/finish/getFinishedTotal', {
                    params: { 
                        homeworkid: homeworkId
                    }
                });
                const submittedCount = finishedTotalResponse.data || 0;

                // 获取未提交作业的总数
                const differenceCountResponse = await axios.get('http://localhost:9999/finish/getDifferenceCount', {
                    params: { 
                        courseclass, 
                        homeworkId 
                    }
                });
                const notSubmittedCount = differenceCountResponse.data || 0;

                // 更新提交情况数据
                this.submissionData.datasets[0].data = [submittedCount, notSubmittedCount];

                console.log('提交情况更新:', {
                    已交人数: submittedCount,
                    未交人数: notSubmittedCount,
                    总人数: submittedCount + notSubmittedCount
                });

                // 获取分数段分布
                const scoreRangeResponse = await axios.get('http://localhost:9999/finish/getFinishRange', {
                    params: { 
                        courseclass: this.selectedCourse, 
                        homeworkid: this.selectedAssignment 
                    }
                });
                
                console.log('成绩分布原始数据:', scoreRangeResponse.data);

                if (scoreRangeResponse.data && scoreRangeResponse.data[0]) {
                    const data = scoreRangeResponse.data[0];
                    
                    // 更新成绩分布数据
                    this.scoreDistribution = {
                        labels: ['0-59', '60-69', '70-79', '80-89', '90-100'],
                        datasets: [{
                            label: '学生人数',
                            data: [
                                parseInt(data.a) || 0,
                                parseInt(data.b) || 0,
                                parseInt(data.c) || 0,
                                parseInt(data.d) || 0,
                                parseInt(data.e) || 0
                            ],
                            backgroundColor: '#409EFF'
                        }]
                    };

                    console.log('更新后的成绩分布数据:', this.scoreDistribution.datasets[0].data);
                }

            } catch (error) {
                console.error('数据分析失败:', error);
                this.$message.error('数据分析失败，请重试！');
                this.resetData();
            }
        },

        resetData() {
            // 重置所有数据到初始状态
            this.maxScore = 0;
            this.minScore = 0;
            this.avgScore = '0.00';
            this.submissionData.datasets[0].data = [0, 0];
            this.scoreDistribution.datasets[0].data = [0, 0, 0, 0, 0];
        },

        async handleCourseChange(value) {
            this.selectedCourse = value;
            this.fetchAssignments();
        },

        handleAssignmentChange(value) {
            console.log('选中的作业ID:', value);
            this.selectedAssignment = value;
        },

        async fetchAssignments() {
            try {
                const response = await axios.get('http://localhost:9999/homework/getHomeworkByClass', {
                    params: {
                        courseclass: this.selectedCourse
                    }
                });
                
                this.assignments = response.data
                    .filter(item => item.courseclass === this.selectedCourse)
                    .map(item => ({
                        id: item.homeworkId,
                        homeworkName: item.homeworkName || item.name
                    }));
                
                this.selectedAssignment = "";
                
                console.log('处理后的作业列表:', this.assignments);
            } catch (error) {
                console.error('获取作业失败:', error);
                this.$message.error('获取作业失败，请重试！');
            }
        },
        
    }
}
</script>

<style scoped>
.data-index {
    padding: 20px;
    background-color: #f9f9f9;
}

.filters {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
    margin-top: 20px;
}

/* 卡片行样式 */
.card-row {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
}

/* 统计卡片样式 */
.stat-card {
    flex: 1;
    min-width: 300px;
}

/* 图表卡片样式 */
.chart-card {
    flex: 1;
    min-width: 300px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.stat-content {
    padding: 10px 0;
}

.stat-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    line-height: 24px;
}

.stat-item:last-child {
    margin-bottom: 0;
}

.label {
    color: #606266;
}

.value {
    font-weight: bold;
    color: #409EFF;
}

h3 {
    margin-top: 0;
    margin-bottom: 20px;
    font-size: 16px;
    font-weight: 500;
}
</style>
